using UnityEngine;

/// <summary>
/// 摄像机跟随玩家移动的脚本，包含边界限制功能
/// 挂载到Main Camera对象上使用
/// </summary>
public class CameraFollow : MonoBehaviour
{
    /// <summary>玩家的Transform组件</summary>
    [Tooltip("玩家对象的Transform组件，需要在Inspector中手动指定")]
    public Transform playerTransform;

    /// <summary>摄像机与玩家之间的偏移量</summary>
    [Tooltip("摄像机相对于玩家的位置偏移")]
    public Vector3 offset = new Vector3(0, 0, -10);

    /// <summary>平滑移动的时间系数，值越小跟随越灵敏</summary>
    [Tooltip("摄像机平滑移动的时间系数，值越小跟随越灵敏")]
    public float smoothTime = 0.3f;

    /// <summary>左边界限制</summary>
    [Tooltip("摄像机允许移动的最左位置")]
    public float leftLimit = -10f;

    /// <summary>右边界限制</summary>
    [Tooltip("摄像机允许移动的最右位置")]
    public float rightLimit = 10f;

    /// <summary>下边界限制</summary>
    [Tooltip("摄像机允许移动的最下位置")]
    public float bottomLimit = -5f;

    /// <summary>上边界限制</summary>
    [Tooltip("摄像机允许移动的最上位置")]
    public float topLimit = 5f;

    /// <summary>平滑移动的速度缓存变量</summary>
    private Vector3 velocity = Vector3.zero;

    /// <summary>
    /// 延迟更新，确保在玩家移动后再更新摄像机位置
    /// </summary>
    void LateUpdate()
    {
        // 检查玩家是否已指定
        if (playerTransform == null)
        {
            Debug.LogWarning("请在Inspector面板中为摄像机指定玩家对象的Transform组件");
            return;
        }

        // 计算目标位置（玩家位置加上偏移量）
        Vector3 targetPosition = playerTransform.position + offset;

        // 限制摄像机在设定范围内移动
        targetPosition.x = Mathf.Clamp(targetPosition.x, leftLimit, rightLimit);
        targetPosition.y = Mathf.Clamp(targetPosition.y, bottomLimit, topLimit);

        // 使用平滑阻尼函数实现平滑跟随效果
        transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime);
    }

    /// <summary>
    /// 在Scene视图中绘制边界范围Gizmos
    /// </summary>
    void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.red;
        // 绘制边界矩形
        Gizmos.DrawLine(new Vector3(leftLimit, topLimit, 0), new Vector3(rightLimit, topLimit, 0));
        Gizmos.DrawLine(new Vector3(rightLimit, topLimit, 0), new Vector3(rightLimit, bottomLimit, 0));
        Gizmos.DrawLine(new Vector3(rightLimit, bottomLimit, 0), new Vector3(leftLimit, bottomLimit, 0));
        Gizmos.DrawLine(new Vector3(leftLimit, bottomLimit, 0), new Vector3(leftLimit, topLimit, 0));
    }
}